package org.gnome.wsgalaxy.gnodroid;

import org.json.JSONObject;

import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class ServiceConnection extends ServiceBase {
    Socket m_socket = null;
    boolean m_exit = false;

    byte[] m_feedDogData = null;

    ServiceConnection()
    {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("service", "Connection");
            jsonObject.put("method", "FeedDog");
            String jsonStr = jsonObject.toString();
            byte[] jsonData = jsonStr.getBytes("UTF-8");
            byte[] data = new byte[jsonData.length + 4 + 1];        //添加一个长度前缀，一个'\0'后缀
            ByteBuffer byteBuffer = ByteBuffer.wrap(data);
            byteBuffer.order(ByteOrder.BIG_ENDIAN);
            byteBuffer.clear();
            byteBuffer.putInt(jsonData.length + 1);
            byteBuffer.put(jsonData);
            byteBuffer.put((byte) 0);
            m_feedDogData = data;
        } catch (Exception e) {}
    }

    @Override
    public void
    start(byte[] data, Socket socket)
    {
        m_socket = socket;

        while (true) {
            try {
                //m_socket.setSoTimeout(1000);
                /*
                try {
                    byte[] buffSize = new byte[4];

                } catch (Exception e) {
                }
                */
                //feed dog per second
                OutputStream outStream = m_socket.getOutputStream();
                outStream.write(m_feedDogData);
                Thread.sleep(1000);
            } catch (Exception e) {
                m_exit = true;
            } finally {}

            //exit while
            if (m_exit) {
                try {
                    m_socket.close();
                } catch (Exception e) {}
                break;
            }

        }
    }
}
